package top.scsoul.voes.web.controller.system;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.scsoul.voes.common.core.domain.AjaxResult;
import top.scsoul.voes.common.core.domain.model.IdsVo;
import top.scsoul.voes.common.core.domain.model.UserSearchVo;
import top.scsoul.voes.common.core.domain.model.UserVo;
import top.scsoul.voes.common.core.domain.model.LoginUser;
import top.scsoul.voes.common.exception.SystemException;
import top.scsoul.voes.framework.web.service.TokenService;
import top.scsoul.voes.framework.web.service.UserLoginService;
import top.scsoul.voes.common.core.domain.entity.User;
import top.scsoul.voes.system.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    UserLoginService userLoginService;

    @Autowired
    UserService userService;
    @Autowired
    TokenService tokenService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @RequestMapping("/login")
    public AjaxResult login(@Valid LoginUser loginUser) {
        User user = userLoginService.login(loginUser);
        if (user == null) {
            return AjaxResult.error("登录失败");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", user.getUsername());
        String token = tokenService.createToken(map);
        map.clear();
        map.put("user", user);
        map.put("token", token);
        return AjaxResult.success(map);
    }

    @RequestMapping("/user/users")
    public AjaxResult users(
            UserSearchVo userSearchVo,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        System.out.println("users检查");
        PageInfo<User> userPageInfo = userService.queryAll(userSearchVo, currentPage, pageSize);

        return AjaxResult.success(userPageInfo);
    }

    @RequestMapping("/user/get/{id}")
    public AjaxResult userById(@PathVariable("id") Integer id) {
        log.info("id{}", id);
        User user = userService.queryById(id);
        return AjaxResult.success(user);
    }

    @RequestMapping("/user/add")
    public AjaxResult add(@Valid UserVo userVo) {
        log.info("{}", userVo);
        userService.insert(userVo);
        return AjaxResult.success();
    }

    @RequestMapping("/user/delete")
    public AjaxResult delete(int id) {
        userService.deleteById(id);
        return AjaxResult.success();
    }

    @RequestMapping("/user/deletes")
    public AjaxResult deletes(@Valid IdsVo idsVo) {
        List<Integer> ids = idsVo.getIds();
        log.info("ids:{}", ids);
        userService.deleteByIds(ids);
        return AjaxResult.success();
    }

    @RequestMapping("/user/update")
    public AjaxResult update(@Valid UserVo userVo) {
        User user = userService.update(userVo);
        return AjaxResult.success(user);
    }


    @RequestMapping("/user/resetPassword")
    public AjaxResult resetPassword(
            @NotEmpty String username,
            @Length(min = 6, max = 100, message = "密码应该在6-100个字符之间") String password) {
        return userService.resetPassword(username, password) ?
                AjaxResult.success() : AjaxResult.error("修改失败");
    }

    @RequestMapping("/user/export")
    public void userExport(@Valid IdsVo idsVo, HttpServletResponse response) throws IOException {
        userService.exportUser(idsVo.getIds(), response);
    }

    @RequestMapping("/user/import")
    public AjaxResult userImport(MultipartFile file) throws Exception {
        Map<String, Object> map = userService.importUser(file);
        return AjaxResult.success(map);
    }

    @RequestMapping("/user/getImportExcel")
    public void importExcelDownload(HttpServletResponse response) throws Exception {
        userService.getImportExcel(response);
    }


    @RequestMapping("/user/self/update")
    public AjaxResult selfUpdate(
            HttpServletRequest request,
            @Valid UserVo userVo) {
        String username = tokenService.getUsername(request);
        User user = new User();
        user.setUsername(username);
        user.setName(userVo.getName());
        user.setGender(userVo.getGender());
        user.setIdCard(userVo.getIdCard());
        user.setPhone(userVo.getPhone());
        return AjaxResult.success(userService.update(user));
    }

    @RequestMapping("/user/self/resetPsw")
    public AjaxResult selfResetPsw(HttpServletRequest request,
                                   String oldPassword,
                                   String newPassword) {
        String username = tokenService.getUsername(request);
        if (newPassword.length() < 6 || newPassword.length() > 100) {
            throw new SystemException("密码长度在6-100位之间");
        }
        return AjaxResult.success(userService.selfResetPsw(username, oldPassword, newPassword));
    }
}
